<template>
	<view class="user-pages-choose-city">
		<!-- #ifndef H5 -->
		<uni-nav-bar :fixed="true" :shadow="false" :statusBar="true" leftIcon="icon-left" title="选择城市" color="#000"
			backgroundColor="">
		</uni-nav-bar>
		<!-- #endif -->

		<fixed @height="initFixHeight">
			<view class="fill-base">
				<!-- #ifndef H5 -->
				<image class="abs choose-bg" :src="`https://www.peikangbao.cn/admin/anmo/mine/choose-addr-bg.png`">
				</image>
				<view :style="{height:`${configInfo.navBarHeight}px`}"></view>
				<!-- #endif -->
				<view class="fill-base pd-lg rel" style="border-radius: 40rpx 40rpx 0 0;">
					<search @input="toSearch" type="input" :padding="0" :radius="30" height="70rpx"
						:confirmSearch="true" placeholder="请搜索城市/区县">
					</search>
				</view>
			</view>
		</fixed>

		<view class="citylist rel" :style="{'height':(windowH - popupHeight)+'px'}">
			<scroll-view style="height: 100%;" scroll-y="true" :scroll-into-view="changeTab" show-scrollbar="false"
				@scroll="scroll">
				<view class="city-list-container">
					<!-- 城市列表 -->
					<view id="citytitle" class="city-list-content">
						<view class="city_title_wrap" v-for="(city,cindex) in citylist" :key="cindex">
							<view :id="['changeTab' + cindex]" class="city-title flex-y-center ml-lg f-ms-title">
								{{city.key}}
							</view>
							<view class="city-list-block">
								<view class="city-item flex-y-center f-paragraph" v-for="(item,index) in city.list"
									:key="index" @tap.stop="selectedCity(cindex,index)">
									{{item}}
								</view>
							</view>
						</view>
						<!-- #ifdef H5 -->
						<abnor :percent="`calc(100vh - 130rpx)`" v-if="citylist.length==0"></abnor>
						<!-- #endif -->
						<!-- #ifndef H5 -->
						<abnor :percent="`calc(100vh - 130rpx - ${configInfo.navBarHeight}px)`"
							v-if="citylist.length==0"></abnor>
						<!-- #endif -->
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 侧边栏导航 -->
		<view class="navrightcity f-caption">
			<!-- #ifndef H5 -->
			<view :style="{height:(popupHeight - configInfo.navBarHeight)+'px'}"></view>
			<!-- #endif -->
			<view v-for="(item,index) in citylist" :key="index" class="nav-item text-bold" :style="{color:primaryColor}"
				@tap.stop="tabChange(index)" @touchend.stop="searchEnd">
				{{item.key}}
			</view>
		</view>
		<!-- 居中首字母样式 -->
		<view class="fix cont_Letter flex-center f-big-title radius-10" v-if="isShowLetter && title[currentIndex]">
			{{title[currentIndex]}}
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from 'vuex';
	import {
		pinyin
	} from "pinyin-pro";
	export default {
		data() {
			return {
				options: {},
				windowH: '',
				popupHeight: '',
				city: [],
				scrollY: -1, //滚动记录
				title: [],
				citylist: {},
				currentIndex: 0,
				isShowLetter: false,
				type: -1,
				curr_city: '',
				changeTab: '',
			}
		},
		computed: mapState({
			configInfo: state => state.config.configInfo,
			technicianParam: state => state.technician.param,
		}),
		async onLoad(options) {
			let {
				type = 0
			} = options
			options.type = type * 1
			this.options = options
			let sysInfo = uni.getSystemInfoSync()
			this.windowH = sysInfo.windowHeight
			await this.initIndex()
			this.$util.setNavigationBarColor({
				bg: this.primaryColor,
				color: '#000000'
			})
			uni.setNavigationBarTitle({
				title: `选择服务地址`
			})
			// #ifdef H5
			this.$jweixin.hideOptionMenu()
			// #endif
		},
		methods: {
			...mapMutations(['updateUserItem', 'updateServiceItem', 'updateTechnicianItem',
				'updateMapItem', 'updateShopstoreItem', 'updateDynamicItem'
			]),
			async initIndex(refresh = false) {
				let data = await this.$api.base.getCityList()
				data.map(item => {
					item.address = item.title
				})
				this.city = data
				this.toSortCity(data)
			},
			initRefresh() {
				this.initIndex(true)
			},
			toSearch(val = '') {
				val = val ? val.replace(/(^\s*)|(\s*$)/g, "") : ''
				let data = !val ? this.city : this.city.filter(item => {
					return item.title.includes(val)
				})
				this.toSortCity(data)
			},
			async toSortCity(data) {
				let arr = data.map(aitem => {
					return `${aitem.title}_id_${aitem.id}`
				})
				this.citylist = this.sortByFirstLetter(arr)
				let title = []
				for (let i in this.citylist) {
					title.push(this.citylist[i].key)
				}
				this.title = title
			},
			initFixHeight(val) {
				this.popupHeight = val
			},
			// 滚动条Y距离
			scroll(e) {
				this.scrollY = e.detail && e.detail.scrollTop
			},
			// 滚动到指定位置
			tabChange(index) {
				if (index == this.currentIndex * 1) {
					this.currentIndex = ''
					this.changeTab = ''
				}
				this.$nextTick(() => {
					this.currentIndex = index
					this.changeTab = `changeTab${index}`
					this.isShowLetter = true
				})
			},
			/* 检索字母拖动结束 */
			searchEnd() {
				setTimeout(() => {
					this.isShowLetter = false
				}, 1000)
			},
			selectedCity(index, aindex) {
				let id = this.citylist[index].id[aindex]
				this.updateTechnicianItem({
					key: 'cityId',
					val: id
				})
				let val = this.city.filter(item => {
					return item.id == id
				})[0]
				this.updateUserItem({
					key: 'city_info',
					val
				})
				let param = Object.assign({}, this.technicianParam, {
					city_id: id
				})
				this.updateTechnicianItem({
					key: 'param',
					val: param
				})
				this.updateUserItem({
					key: 'location',
					val
				})

				let pages = getCurrentPages()
				let len = pages.length
				let prePage = ''
				if (len > 1) {
					prePage = pages[pages.length - 2].route
				}
				console.log(len, pages, "===pages len")
				let updateArr = ['updateServiceItem',
					'updateMapItem', 'updateShopstoreItem', 'updateDynamicItem'
				]
				updateArr.map(item => {
					this[item]({
						key: 'pageActive',
						val: false
					})
				})
				let pagesArr = ['pages/technician', 'user/pages/choose-technician']
				let {
					type
				} = this.options
				if (pagesArr.includes(prePage) || type > 1) {
					if (type > 1) {
						this.updateUserItem({
							key: 'changeAddr',
							val: true
						})
					}
					let methodModel = type > 1 ? 'initRefresh' : 'toChooseLocation'
					this.$util.getPage(-1)[methodModel]()
					let {
						realtime_location = 0
					} = this.configInfo
					if (type == 3 && realtime_location && len > 2 && pages[pages.length - 3].route == 'pages/service') {
						this.$util.getPage(-2)[methodModel]()
					}
					this.$util.goUrl({
						url: 1,
						openType: `navigateBack`
					})
				} else {
					this.updateUserItem({
						key: 'changeAddr',
						val: true
					})
					this.$util.goUrl({
						url: `/${pagesArr[type]}`,
						openType: `reLaunch`
					})
				}
			},
			sortByFirstLetter(origin) {
				origin = origin.sort((pre, next) => pinyin(pre, {
					pattern: 'first',
					toneType: 'none',
				}).localeCompare(pinyin(next, {
					pattern: 'first',
					toneType: 'none',
				})))

				const newArr = []
				origin.map(item => {
					// 取首字母
					const key = pinyin(item, {
						pattern: 'first',
						toneType: 'none',
					}).charAt(0).toUpperCase()
					const index = newArr.findIndex(subItem => subItem.key === key)
					let arr = item.split('_id_')
					item = arr[0]
					let id = arr[1]
					if (index < 0) {
						newArr.push({
							key: key,
							list: [item],
							id: [id]
						})
					} else {
						newArr[index].list.push(item)
						newArr[index].id.push(id)
					}
				})

				return newArr
			}
		}
	}
</script>

<style lang="scss">
	.user-pages-choose-city {
		.choose-bg {
			width: 100%;
			height: 265rpx;
			top: 0;
			left: 0;
		}

		/* 居中显示的选中首字母 */
		.cont_Letter {
			background-color: #666;
			color: #fff;
			top: 50%;
			left: 50%;
			margin: -50px;
			width: 100px;
			height: 100px;
			z-index: 1
		}


		.navrightcity {
			position: fixed;
			top: 50%;
			transform: translateY(-50%);
			right: 0;
			width: 70rpx;
			z-index: 10;
			text-align: center;

			.nav-item {
				height: 44rpx;
			}
		}

		.citylist {
			width: 100%;
			overflow: hidden;

			.city-list-container {
				width: 100%;
				height: 100%;
				background-color: #F4F6F7;

				.city-title {
					height: 82rpx;
					color: #232323;
				}

				.city-list-block {
					padding: 0 39rpx;
					background-color: #fff;

					.city-item {
						height: 98rpx;
						color: #020202;
						border-bottom: 1px solid #F1F1F1;

						&:last-child {
							border: 0;
						}
					}
				}
			}
		}

	}
</style>